/**
 * @project sso-token-start V1.0
 * @Title:  SsoTokenFilter.java  
 * @Package com.gitee.kinbug.sso.filter 
 * Copyright(c) 2020 KinBug Co. Ltd. 
 * All right reserved. 
 */
package com.gitee.kinbug.sso.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;
import com.gitee.kinbug.sso.handler.TokenLoginHandler;
import com.gitee.kinbug.sso.model.AuthUser;
import com.gitee.kinbug.sso.model.Result;
import com.gitee.kinbug.sso.properties.SsoTokenProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * Description:TODO(sso token 拦截器)
 * @author: KinBug
 */
@Slf4j
public class SsoTokenFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 8498462510464523773L;

	private SsoTokenProperties tokenClientProperties;
	
	private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@SuppressWarnings("unused")
	private String ssoServer;
	private String logoutPath;
	private String excludedPaths;
	
	public SsoTokenFilter(SsoTokenProperties tokenClientProperties) {
		this.tokenClientProperties = tokenClientProperties;
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ssoServer = filterConfig.getInitParameter(tokenClientProperties.getAuthKey());
		logoutPath = filterConfig.getInitParameter(tokenClientProperties.getLogoutPath());
		excludedPaths = filterConfig.getInitParameter(tokenClientProperties.getExcludedPaths());
		log.info("XxlSsoTokenFilter init.");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// make url
		String servletPath = req.getServletPath();

		// excluded path check
		if (excludedPaths != null && excludedPaths.trim().length() > 0) {
			for (String excludedPath : excludedPaths.split(",")) {
				String uriPattern = excludedPath.trim();

				// 支持ANT表达式
				if (antPathMatcher.match(uriPattern, servletPath)) {
					// excluded path, allow
					chain.doFilter(request, response);
					return;
				}

			}
		}
		// logout filter
		if (logoutPath != null && logoutPath.trim().length() > 0 && logoutPath.equals(servletPath)) {

			// logout
			TokenLoginHandler.logout(req);

			// response
			res.setStatus(HttpServletResponse.SC_OK);
			res.setContentType("application/json;charset=UTF-8");
			res.getWriter().println(Result.success("登录成功", null).toJsonString());

			return;
		}
		// login filter
		AuthUser authUser = TokenLoginHandler.loginCheck(req);
		if (authUser == null) {

			// response
			res.setStatus(HttpServletResponse.SC_OK);
			res.setContentType("application/json;charset=UTF-8");
			res.getWriter().println(Result.error("操作失败", null).toJsonString());
			return;
		}
		// ser sso user
		request.setAttribute(tokenClientProperties.getLoginUser(), authUser);
		// already login, allow
		chain.doFilter(request, response);
		return;
	}

}
